package cn.bigfire.wedesk.net.protocol;

import cn.bigfire.wedesk.bean.Wedesk;
import com.alibaba.fastjson.JSON;
import lombok.Data;

@Data
public class Protocol {
    int cmd;
    int type;
    Object obj;

    //没有协议号。返回的时候会原协议返回
    public static  Protocol of(int cmd, Object obj) {
        Protocol protocol = new Protocol();
        protocol.setCmd(cmd);
        protocol.setObj(obj);
        protocol.setType(TypeMapper.getType(obj.getClass()));
        return protocol;
    }

    public static  Protocol of(Wedesk.Cmd cmd, Object obj) {
        Protocol protocol = new Protocol();
        protocol.setCmd(cmd.getValue());
        protocol.setObj(obj);
        protocol.setType(TypeMapper.getType(obj.getClass()));
        return protocol;
    }

    public static  Protocol ofErr(Object obj) {
        Protocol protocol = new Protocol();
        protocol.setType(Wedesk.Type.TYPE_Err.getValue());
        protocol.setObj(obj);
        return protocol;
    }

    //protobuf err
    public static Protocol err(String errMsg) {
        Wedesk.Err err = new Wedesk.Err();
        err.setErrCode(500);
        err.setErrMsg(errMsg);
        return ofErr(err);
    }

    public static Protocol err(int errCode, String errMsg){
        Wedesk.Err err = new Wedesk.Err();
        err.setErrCode(errCode);
        err.setErrMsg(errMsg);
        return ofErr(err);
    }

    public static Protocol err(int cmd,int errCode, String errMsg){
        Wedesk.Err err = new Wedesk.Err();
        err.setErrCode(errCode);
        err.setErrMsg(errMsg);
        return of(cmd, err);
    }

    @Override
    public String toString() {
        return JSON.toJSONString(this);
    }
}
